/**
 * 通用新增
 * @url admin/system/base/add
 * @description 通用新增操作
 */
module.exports = {
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: '新增成功' };
		
		// 表名映射配置
		const dbNameMap = {
			user: 'uni-id-users',
			role: 'uni-id-roles',
			permission: 'uni-id-permissions',
			menu: 'opendb-admin-menus'
		};
		
		// 业务逻辑开始-----------------------------------------------------------
		let { type, ...formData } = data;
		
		if (!type || !dbNameMap[type]) {
			return { code: -1, msg: '类型参数错误' };
		}
		
		let dbName = dbNameMap[type];
		
		// 根据类型进行特殊处理
		if (type === 'role') {
			// 角色新增
			if (!formData.role_id) {
				return { code: -1, msg: '角色ID不能为空' };
			}
			if (!formData.role_name) {
				return { code: -1, msg: '角色名称不能为空' };
			}
			
			// 检查角色ID是否已存在
			let existRole = await db.collection(dbName)
				.where({ role_id: formData.role_id })
				.get();
			if (existRole.data.length > 0) {
				return { code: -1, msg: '角色ID已存在' };
			}
			
			formData.create_date = Date.now();
			await db.collection(dbName).add(formData);
			
		} else if (type === 'permission') {
			// 权限新增
			if (!formData.permission_id) {
				return { code: -1, msg: '权限ID不能为空' };
			}
			if (!formData.permission_name) {
				return { code: -1, msg: '权限名称不能为空' };
			}
			
			// 检查权限ID是否已存在
			let existPerm = await db.collection(dbName)
				.where({ permission_id: formData.permission_id })
				.get();
			if (existPerm.data.length > 0) {
				return { code: -1, msg: '权限ID已存在' };
			}
			
			formData.create_date = Date.now();
			await db.collection(dbName).add(formData);
			
		} else if (type === 'menu') {
			// 菜单新增
			if (!formData.name) {
				return { code: -1, msg: '菜单名称不能为空' };
			}
			
			formData.create_date = Date.now();
			await db.collection(dbName).add(formData);
			
		} else if (type === 'user') {
			// 用户新增（使用 uni-id）
			if (!formData.username) {
				return { code: -1, msg: '用户名不能为空' };
			}
			if (!formData.password) {
				return { code: -1, msg: '密码不能为空' };
			}
			
			// 使用 uni-id 创建用户
			let createRes = await uniID.createUser(formData);
			if (createRes.code !== 0) {
				return { code: -1, msg: createRes.msg || '创建用户失败' };
			}
			res.data = createRes.uid;
		} else {
			// 通用新增
			formData.create_date = Date.now();
			await db.collection(dbName).add(formData);
		}
		
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}

